﻿using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using TSharp.Core;
using TSharp.Core.Repository;
using TSharp.Core.Osgi;
using TSharp.Core.Util;
using System.Linq;
[assembly: RegAppEvent(typeof(MigrateDatabaseHandler))]
//使用此方式注册数据自动迁移，但在开发阶段由于常常在修改模型后忘记签入，而自动运行有导致了数据库迁移，其他人则会发生模型已改变的错误。故暂时放弃此功能
namespace TSharp.Core.Repository
{
    public class MigrateDatabaseHandler : IAppHandler
    {
        public void OnStart(AppEventArgs args)
        {
            if (TSharp.Core.Env.TSharpGlobal.IsDebuggerEnable)
            {
                if ("AutomaticMigrationsEnabled".GetAppSetting(k => k.ToBoolean(false)))
                {
                    var initializer = ModelBuilderManager.BuildMigrateDatabaseToLatestVersionInitializer();
                    ModelBuilderManager.DynamicSetDatabaseInitializer(initializer.Item1, initializer.Item2);
                }
                else if ("SetInitializerNull".GetAppSetting(k => k.ToBoolean(true)))
                {
                    var initializer = (ModelBuilderManager.BuildCreateDatabaseIfNotExistsInitializer());
                    ModelBuilderManager.DynamicSetDatabaseInitializer(initializer.Item1, initializer.Item2);
                }
            }
            else
            {
                var initializer = (ModelBuilderManager.BuildCreateDatabaseIfNotExistsInitializer());
                ModelBuilderManager.DynamicSetDatabaseInitializer(initializer.Item1, initializer.Item2);
            }
        }


        public void OnStop(AppEventArgs args)
        {
        }
    }
}